<template>
  <div style="">
    <div class="container">
      <div style="margin: auto;justify-content: center;align-items: center;width: 1000px">
        <div style="height: 100%;">
          <el-carousel :interval="4000" type="card" height="400px" style="margin-left: 34px">
            <el-carousel-item v-for="(medicine, index) in xiyaomedicines" :key="index">
              <div class="medicine-card1">
                <img
                  :src="medicine.imageUrl"
                  @click="navigateToDetails(medicine.id)"
                  alt="药品图片"
                  width="150px"
                  height="200px"
                  :class="{ 'image-hover-effect': isHovered }"
                  @mouseover="handleMouseOver"
                  @mouseout="handleMouseOut"
                />
                <div style="display: flex"><el-tag size="small">药名:</el-tag><h1 style="font-size: 13px;vertical-align: middle">{{ medicine.name }}</h1></div>
                <div style="display: flex;"><el-tag size="small">别名:</el-tag><p title="别名" style="font-size: 10px;vertical-align: middle">{{medicine.alias}}</p></div>
                <div style="margin-left: 10px; float: right;">
                  <el-link  @click="navigateToDetails(medicine.id)" :underline="false" style="font-size: 16px;border: none">查看详情<i class="el-icon-arrow-right"></i></el-link>
                </div>
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>
      </div>
      <div class="selectype" style="">
        <el-select v-model="skuType"  placeholder="请选择" style="width: 120px" @change="handleSelectType">
          <el-option
            v-for="(item, index) in medicineTypeValue"
            :key="index"
            :label="item.label"
            :value="item.value"
            :disabled="item.disabled">
          </el-option>
        </el-select>
      </div>
      <div class="liu-form-inline" style="">
        <el-form ref="dataEditForm" :inline="true" :model="page" class="demo-form-inline">
          <el-form-item label="">
            <el-autocomplete
              class="autocomplete-border"
              v-model="page.queryString"
              :fetch-suggestions="querySearch"
              placeholder="请输入内容"
              @select="handleSelect"
              ref="autocompleteRef"
              style="width: 100%;margin: 0px;padding: 0px;"
              id="1">
              <template v-slot="{ item }">
                <div>
                  <div class="val"><i class="el-icon-search" style="margin-right: 10px"></i>{{ item.value || item.alias }}</div>
                  <!--                  <div class="val"><i class="el-icon-search" style="margin-right: 10px"></i>{{ item.num }}</div>-->
                </div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="searchMedicine">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div v-if="showCard" class="results" id="searchResults">
        <div class="content-centre">
          <div class="commone-style">
            <div class="medicine-card" v-for="(medicine, index) in medicine2" :key="index">
              <div style="margin-right: 10px; color: black">
                <img
                  :src="medicine.imageUrl"
                  @click="navigateToDetailsInfoliu(medicine.id,medicine.category,medicine.skuId)"
                  alt="药品图片"
                  width="150px"
                  height="200px"
                  :class="{ 'image-hover-effect': isHovered }"
                  @mouseover="handleMouseOver"
                  @mouseout="handleMouseOut"
                />
                <div style="display: flex"><el-tag size="small">药名:</el-tag><h1 style="font-size: 10px;vertical-align: middle">{{ medicine.name }}</h1></div>
                <div class="medicine_title" style="display: flex;"><el-tag size="small">别名:</el-tag><p title="别名" style="font-size: 10px;vertical-align: middle">{{medicine.alias}}</p></div>
                <div style="margin-left: 10px; float: right;">
                  <el-link  @click="navigateToDetailsInfoliu(medicine.id,medicine.category,medicine.skuId)" :underline="false" style="font-size: 16px;border: none">查看详情<i class="el-icon-arrow-right"></i></el-link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="content-centre" style="padding-top: 60px">
        <div class="commone-style">
          <div class="medicine-card" v-for="(medicine, index) in medicines" :key="index">
            <div style="margin-right: 10px;color: black">
              <img
                :src="medicine.imageUrl"
                @click="navigateToDetails(medicine.id)"
                alt="药品图片"
                width="150px"
                height="200px"
                :class="{ 'image-hover-effect': isHovered }"
                @mouseover="handleMouseOver"
                @mouseout="handleMouseOut"
              />
              <div style="display: flex"><el-tag size="small">药名:</el-tag><h1 style="font-size: 13px;vertical-align: middle">{{ medicine.name }}</h1></div>
              <div class="medicine_title" style="display: flex;"><el-tag size="small">别名:</el-tag><p title="别名" style="font-size: 10px;vertical-align: middle">{{medicine.alias}}</p></div>
              <div style="margin-left: 10px; float: right;">
                <el-link  @click="navigateToDetails(medicine.id)" :underline="false" style="font-size: 16px;border: none">查看详情<i class="el-icon-arrow-right"></i></el-link>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="block">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="positionPage.currentPage"
          :page-size="positionPage.pageSize"
          layout="prev, pager, next"
          :total="positionPage.total">
        </el-pagination>
      </div>
    </div>
    <div class="footer">
      <div class="">
        <div style="align-items: center">
          <h2>医药查询助手</h2>
          <p>
            医药查询助手是一款基于医药知识图谱的医药查询工具，
            它可以帮助医生快速查询药品的相关信息，
            并为医生提供药品的推荐。
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { medicine, searchTcMedicineClient, TcMedicineClient } from '@/api/medicine'
// import particlesConfig from '../particles/particles.json'
import { tcCategory } from '@/api/category'
import request from '@/api/request'
export default {
  components: {
    // dataShow,
    // VideoPlayer
  },
  data () {
    return {
      showCard: false,
      isHovered: false,
      selectedValue: null,
      skuType: '',
      medicineTypeValue: [
        {
          value: '1',
          label: '中药材'
        },
        {
          value: '3',
          label: '中成药'
        },
        {
          value: '2',
          label: '西药'
        }
      ],
      // imageUrl: '',
      medicineInput: '',
      formData: {},
      searchResult: '',
      // medicines: [],
      medicines: [],
      xiyaomedicines: {},
      medicine2: [],
      list: {},
      categoryMedicineList: [],
      page: {
        total: 7,
        currentPage: 1,
        pageSize: 3,
        queryString: ''
      },
      positionPage: {
        total: 7,
        currentPage: 1,
        pageSize: 2,
        queryString: ''
      },
      positionPage2: {
        totalCount: 7,
        pageNo: 1,
        pageSize: 12
      },
      hardcodedSuggestions: [{ value: '土地', num: 7 }, { value: '行政', num: 4 }, { value: '案件', num: 3 }],
      keywords: ''
    }
  },
  created () {
    // this.getData()
    this.searchMedicineList()
    this.categoryMedicine()
    this.List()
    this.xiyaosearchMedicineList()
  },
  mounted () {
    // this.init()
    // this.initParticlesEffect()
  },
  methods: {
    // init () {
    //   // window.particlesJS('particles-js', particlesConfig)
    //   window.particlesJS('particles-js', particlesConfig)
    //   document.body.style.overflow = 'hidden'
    // },
    querySearch (queryString, cb) {
      const restaurants = this.hardcodedSuggestions
      const results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      cb(results)
    },
    createFilter (queryString) {
      return (restaurant) => {
        // 在调用 toLowerCase 之前检查是否为 null
        return restaurant.value && restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      }
    },
    handleSelect (item) {
      // console.log(item)
    },
    navigateToDetails (id) {
      alert(id)
      // this.$router.push({ name: 'details', query: { id } })
      const frontToken = localStorage.getItem('ordinaryUserToken')
      // alert(frontToken)
      const backToken = localStorage.getItem('token')
      // alert(backToken)
      if (frontToken === null && backToken === null) {
        this.$eventBus.$emit('medicineDetails')// 触发事件 进入详情页 需要先登录 后台登陆后在查看详情页面就不需要再次登录
      } else if (this.medicine2.skuId === 1) {
        // this.$router.push({ name: 'westernMedicineThemeDetails', params: { id: id } })
        this.$router.push({
          name: 'traditionalChineseMedicineDetails',
          params: {
            id: id
          }
        })
      } else if (this.medicine2.skuId === 2) {
        this.$router.push({
          name: 'westernMedicineThemeDetails',
          params: {
            id: id
          }
        })
      } else if (this.medicine2.skuId === 3) {
        this.$router.push({
          name: 'proprietaryChineseMedicinesDeatils',
          params: {
            id: id
          }
        })
      }
    },
    navigateToDetailsInfoliu (id, category, skuId) {
      // this.$router.push({ name: 'traditionalChineseMedicineDetails', params: { id: id } })
      if (skuId === '1') {
        this.$router.push({ name: 'traditionalChineseMedicineDetails', params: { id: id } })
        return
      }
      if (skuId === '2') {
        this.$router.push({ name: 'westernMedicineThemeDetails', params: { id: id } })
        return
      }
      if (skuId === '3') {
        this.$router.push({ name: 'proprietaryChineseMedicinesDeatils', params: { id: id } })
      }
    },
    async searchMedicine () {
      if (this.page.queryString === '') {
        this.$message({
          message: '请输入药品名称',
          type: 'warning',
          center: true
        })
        return
      }
      const queryString = this.page.queryString
      const page = this.page.currentPage
      const size = this.page.pageSize
      try {
        await request.get(`/search/getInfo/clients/${page}/${size}?queryString=${queryString}`).then(resp => {
          const data = resp.data
          this.medicine2 = data.data
          this.showCard = true
          // console.log(this.medicines)
          // this.medicines = data.data.map(item => item.medicine)
        })
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    async searchMedicines () {
      const frontToken = localStorage.getItem('ordinaryUserToken')
      const backToken = localStorage.getItem('token')
      if (frontToken === null && backToken === null) {
        this.$eventBus.$emit('medicineDetails')
        return
      }
      if (this.page.queryString === '') {
        this.$message({
          message: '请输入药品名称',
          type: 'warning',
          center: true
        })
        return
      }
      const classData = {
        currentPage: this.page.currentPage,
        pageSize: this.page.pageSize,
        category: this.page.queryString
      }
      try {
        await searchTcMedicineClient(classData).then(resp => {
          const data = resp.data
          this.medicine2 = data.rows
          this.showCard = true
          // console.log(this.medicines)
          // this.medicines = data.data.map(item => item.medicine)
        })
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    async xiyaosearchMedicineList () {
      const classData = {
        currentPage: this.positionPage.currentPage,
        pageSize: this.positionPage.pageSize,
        queryString: this.positionPage.queryString
      }
      try {
        await medicine(classData).then(resp => {
          const data = resp.data
          this.positionPage.total = data.total
          // this.medicine2 = data.rows
          this.xiyaomedicines = data.rows
          // this.hardcodedSuggestions = data.rows.map(item => ({ value: item.name, alias: item.alias }))
          // console.log(this.medicines)
          // this.medicines = data.data.map(item => item.medicine)
        })
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    async searchMedicineList () {
      const classData = {
        currentPage: this.positionPage.currentPage,
        pageSize: this.positionPage.pageSize,
        queryString: this.positionPage.queryString
      }
      try {
        await TcMedicineClient(classData).then(resp => {
          const data = resp.data
          this.positionPage.total = data.total
          // this.medicine2 = data.rows
          this.medicines = data.rows
          this.hardcodedSuggestions = data.rows.map(item => ({ value: item.name, alias: item.alias }))
          // console.log(this.medicines)
          // this.medicines = data.data.map(item => item.medicine)
          // this.$nextTick(() => {
          //   this.initParticlesEffect()
          // })
        })
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    async List () {
      try {
        const pageNo = this.positionPage2.pageNo
        const pageSize = this.positionPage2.pageSize
        // https://server.dayi.org.cn/api/cmedical/list2?pageNo=1&pageSize=10
        await this.$axiosApi.myAxios.get('api/cmedical/list2?' + 'pageNo=' + pageNo + '&' + 'pageSize=' + pageSize).then(resp => {
          const data = resp.data
          this.positionPage2.totalCount = data.totalCount
          // this.medicine2 = data.rows
          this.list = data.list
          // alert(data.list)
          // this.hardcodedSuggestions = data.rows.map(item => ({ value: item.name, alias: item.alias }))
          // console.log(this.medicines)
          // this.medicines = data.data.map(item => item.medicine)
        })
      } catch (error) {
        this.handleAxiosError(error)
      }
    },
    westernMedicine () {
      const frontToken = localStorage.getItem('ordinaryUserToken')
      const backToken = localStorage.getItem('token')
      if (frontToken === null && backToken === null) {
        this.$eventBus.$emit('medicineDetails')
        return
      }
      this.$router.push('/westernMedicine.html')
    },
    tranditionalMedicineCategoryView () {
      const frontToken = localStorage.getItem('ordinaryUserToken')
      const backToken = localStorage.getItem('token')
      if (frontToken === null && backToken === null) {
        this.$eventBus.$emit('medicineDetails')
        return
      }
      this.$router.push('/tranditionalMedicineCategory.html')
    },
    // 获取分类
    categoryMedicine () {
      tcCategory().then(resp => {
        this.categoryMedicineList = resp.data.map(item => item.category)
        // alert(this.categoryMedicineList)
      }).catch(error => {
        this.handleAxiosError(error)
      })
    },
    navigateToCategory (category) {
      const frontToken = localStorage.getItem('ordinaryUserToken')
      const backToken = localStorage.getItem('token')
      if (frontToken === null && backToken === null) {
        this.$eventBus.$emit('medicineDetails')
        return
      }
      this.$router.push({ name: 'cagetoryMedicine', params: { category } })
    },
    // initParticlesEffect () {
    //   window.particlesJS('particles-js', particlesConfig)
    // },
    handleAxiosError (error) {
      // 检查是否是Axios的网络错误
      if (error.isAxiosError && error.response) {
        // 处理您的网络错误，例如显示用户友好的提示
        this.$message.error('网络请求失败，请稍后重试')
      } else {
        // 处理其他类型的错误
        this.$message.error('网络请求失败，发生错误，请稍后重试')
      }
    },
    detile () {
      // console.log('详情')
      this.$router.push('/details')
    },
    // 客户端搜索
    handleSelectType (value) {
      alert(value)
    },
    handleSizeChange (pageSize) {
      this.positionPage.pageSize = pageSize
      this.searchMedicineList()
    },
    handleCurrentChange (currentPage) {
      this.positionPage.currentPage = currentPage
      this.searchMedicineList()
    },
    handleSizeChange2 (pageSize) {
      this.positionPage2.pageSizes = pageSize
      this.List()
    },
    handleCurrentChange2 (pageNo) {
      this.positionPage2.pageNo = pageNo
      this.List()
    },
    currentPage3 () {},
    handleMouseOver () {
      this.isHovered = true
    },
    handleMouseOut () {
      this.isHovered = false
    }
  }
}
</script>

<style lang="stylus" scoped>
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
.no-underline {
  text-decoration: none;
}

.no-underline:hover {
  text-decoration: none;
}
.el-tag {
  margin: 5px 0px 5px 0px ;
}
.el-link--inner {
  color: #1984dc;
}
.el-link:hover {
  color: #0ed5a6;
}

.medicine-card1 {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 8px;
  width: 40%;
  text-align: center;
  height: 80%;
  flex: none;
}
.textp {
  p{
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
  }
}
.autocomplete-border .elinput {
  border: none;
  box-shadow: none;
  border-radius: 0;
}
.autocomplete-border .el-autocomplete-suggestion {
}

@import "../../../assets/css/webpage.css";

.image-hover-effect {
  transition: transform 0.3s ease-out;
}
.image-hover-effect:hover {
  transform: scale(1.1);
}
.title_intrduction p {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
.medicine_title p {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}
.selectype {
  display: flex;
  margin: 21px 2px 2px 300px;
  .el-input {
    width: 200px;
  }
}
</style>
